/*
 * File    : /part1/model.instance.js
 * Time    : 2021-03-21 20:06:19
 * Author  : Gray Snail
 * Version : 1.0
 * Contact : shtao2011@sina.com
 * License : Copyright (c) 2021 Gray Snail
 * Desc    : None
 */

const { Sequelize, Model, DataTypes } = require('sequelize')

const sequelize = new Sequelize('sqlite::memory:', {
    logging: console.log,
})

class User extends Model {}

User.init(
    {
        name: DataTypes.TEXT,
        favoriteColor: {
            type: DataTypes.TEXT,
            defaultValue: 'green',
        },
        age: DataTypes.INTEGER,
        cash: DataTypes.INTEGER,
    },
    {
        sequelize,
        modelName: 'User',
    },
)
;(async () => {
    await sequelize.sync({ force: true })

    const jane = User.build({ name: 'Jane', age: 10, cash: 120 })
    await jane.save()
    console.log(jane instanceof User)
    console.log(jane.name)
    console.log('Jane was saved to the db')

    /************************/
    const jane1 = await User.create({ name: 'Jane' })

    jane1.name = 'Ada'
    await jane1.save()
    console.log(jane1.toJSON())
    console.log(JSON.stringify(jane1, null, 4))

    /*******************delete****************/
    const delRes = await jane1.destroy()

    /********************reload***************/
    jane.name = 'Ada'
    await jane.reload()
    console.log(jane.toJSON())

    /*********************save field*********/
    jane.name = 'Jane II'
    jane.favoriteColor = 'black'
    await jane.save({ fields: ['name'] })
    console.log(jane.toJSON())

    await jane.reload()
    console.log(jane.toJSON())

    /********************increment*********/
    await jane.increment('age', { by: 2 })
    console.log(jane.toJSON())

    await jane.increment({ age: 2, cash: 12 })
    console.log(jane.toJSON())

    await jane.reload()
    console.log(jane.toJSON())
})()
